#include"TurnSequenceWidget.h" 

#include"Unit.h"

#include<assert.h>

TurnSequenceWidget::TurnSequenceWidget(const QList<Unit*> &turnSequence, QWidget *parent):QListWidget(parent){
	for(int i = 0; i < turnSequence.size(); i++){
		QString text = turnSequence[i]->name() + "\n" + QString().setNum(turnSequence[i]->health()) + "/10 hp";
		QListWidgetItem *item = new QListWidgetItem(text, this);
		if(turnSequence[i]->team() == TEAM_A)
			item->setForeground(QBrush(Qt::blue));
		else
			item->setForeground(QBrush(Qt::red));
		item->setData(Qt::UserRole, QVariant::fromValue((long unsigned)turnSequence[i]));
		addItem(item);
		
	}
	setCurrentRow(0);
	setSizePolicy(QSizePolicy::Preferred, QSizePolicy::MinimumExpanding);
}

TurnSequenceWidget::~TurnSequenceWidget(){
	
}

void TurnSequenceWidget::slotTurnEnded(Unit *unit){
	if(unit == (Unit*)item(0)->data(Qt::UserRole).toULongLong()){
		QListWidgetItem *item = takeItem(0);
		addItem(item);
	}else{
		assert(false);
		//This shouldn't happen.
	}
	setCurrentRow(0);
}

void TurnSequenceWidget::slotUnitDamaged(Unit *unit){
	QString text = unit->name() + "\n" + QString().setNum(unit->health() > 0 ? unit->health() : 0) + "/10 hp";
	for(int i = 0; i < count(); i++){
		if(unit == (Unit*) (item(i)->data(Qt::UserRole).toULongLong()) ){
			item(i)->setText(text);
			item(i)->setIcon(QIcon::fromTheme("window-close"));
			if(unit->health() > 0){//Pointless if it would be deleted immediately...
				m_items.push_back(item(i));
				QTimer *timer = new QTimer(this);
				timer->setSingleShot(true);
				connect(timer, SIGNAL(timeout()), this, SLOT(slotTimerTimeout()));
				m_timers.push_back(timer);
				timer->start(1000);
			}
			break;
		}
	}
}

void TurnSequenceWidget::slotUnitDied(Unit *unit){
	for(int i = 0; i < count(); i++){
		if(unit == (Unit*) (item(i)->data(Qt::UserRole).toULongLong()) ){
			/*QListWidgetItem *item = */takeItem(i);
			//WARNING: Yes I know. By not deleting it, we get a minor memory leak. Qt is being a bitch about deleting it
			break;
		}
	}
}

void TurnSequenceWidget::slotTimerTimeout(){
	delete m_timers.takeAt(0);
	QListWidgetItem* item = m_items.takeAt(0);
	item->setIcon(QIcon());
}
